package com.zztl.infiniteBand.ui.activity

import android.app.AlarmManager
import android.app.PendingIntent
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothGatt
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.SystemClock
import android.view.KeyEvent
import android.widget.CompoundButton
import butterknife.OnCheckedChanged
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleConnectCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.githang.statusbar.StatusBarCompat
import com.tencent.bugly.beta.Beta
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseFragment
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.eventbus.BluetoothSwitchEvent
import com.zztl.infiniteBand.eventbus.ConnectedEvent
import com.zztl.infiniteBand.eventbus.LanguageEvent
import com.zztl.infiniteBand.eventbus.RefreshAssetsEvent
import com.zztl.infiniteBand.model.ContactInfoBean
import com.zztl.infiniteBand.model.FirmwareVersionBean
import com.zztl.infiniteBand.model.VersionResponseBean
import com.zztl.infiniteBand.presenter.SyncStepPresenter
import com.zztl.infiniteBand.receiver.AlarmReceiver
import com.zztl.infiniteBand.receiver.BluetoothConnectReciver
import com.zztl.infiniteBand.service.NLService
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.Constans
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.ui.fragment.MineFragment
import com.zztl.infiniteBand.ui.fragment.MiningFragment
import com.zztl.infiniteBand.ui.fragment.SportFragment
import com.zztl.infiniteBand.ui.view.mvpview.ContactInfoView
import com.zztl.infiniteBand.util.AppInfoUtils
import com.zztl.infiniteBand.util.LogUtils
import com.zztl.infiniteBand.util.PermissionUtils
import com.zztl.infiniteBand.util.device.DeviceUtil
import com.zztl.infiniteBand.util.toast
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MainActivity : BaseMvpActivity<ContactInfoView, SyncStepPresenter>(), ContactInfoView {

        companion object {
            var reStart=false
           fun reStart(context:Context) {
               val intent = Intent(context, MainActivity::class.java).apply {
                   flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
               }
               reStart=true
               context.startActivity(intent)

           }
        }

    var currentFragment: BaseFragment? = null
    var isFirstOnBluetooth: Boolean = false

    lateinit var mSportFragment: SportFragment

    lateinit var mMineFragment: MineFragment
    lateinit var mMiningFragment: MiningFragment




    lateinit var mSyncStepPresenter: SyncStepPresenter


    val mManager by lazy {
        getSystemService(ALARM_SERVICE) as AlarmManager
    }

    val mConnectReciver by lazy {
        BluetoothConnectReciver()
    }




    lateinit var mPendingIntent: PendingIntent

    private var isFirstToMining: Boolean = true//第一次去挖矿界面


    private var currentMilli: Long = 0

    private val bleConnectCallback = object : BleConnectCallback() {
        override fun onStartConnect() {

        }

        override fun onConnectFail(bleDevice: BleDevice?, exception: BleException?) {

        }

        override fun onConnectSuccess(bleDevice: BleDevice?, gatt: BluetoothGatt?, status: Int) {

            EventBus.getDefault().post(ConnectedEvent(true))
        }

        override fun onDisConnected(isActiveDisConnected: Boolean, device: BleDevice?, gatt: BluetoothGatt?, status: Int) {
            EventBus.getDefault().post(ConnectedEvent(false))
        }
    }


    override fun setLayoutId(): Int = R.layout.activity_main


    override fun initBase() {
        mMiningFragment = MiningFragment()
        mSportFragment = SportFragment()
        mMineFragment = MineFragment()
        mining.isChecked = true
        startAlarm()
        registerReceiver()
        mSyncStepPresenter.getContactInfo(this)
        mSyncStepPresenter.getVersion(this)

        toggleNotificationListenerService()
        PermissionUtils.requestMultiPermissions(this, mPermissionGrant, PermissionUtils.CODE_INIT_PERMISSION)
        if(reStart){
            reStart=false
            mine.isChecked=true
        }
    }



    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_MULTI_PERMISSION -> try {
                    if (!DeviceUtil.bluetoothIsEnabel()) {
                        isFirstOnBluetooth = true
                        DeviceUtil.openBluetooth()
                    } else {
                        LogUtils.i("swl", "上次保留的设备" + DeviceUtil.getLastConnectMac())
                        if (DeviceUtil.getLastConnectMac().isNotEmpty()) {
                            if (BleManager.getInstance().isSupportBle) {
                                BleManager.getInstance().connect(DeviceUtil.getLastConnectMac(), bleConnectCallback)
                            }
                        }
                    }

                } catch (e: Exception) {
                }

            }
        }
    }


 /*   override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        outState?.putParcelable("android:support:fragments", null)
    }*/

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)
    }






    /**
     * 开启获取步数的周期定时任务
     */
    private fun startAlarm() {
        val triggerAtTime = SystemClock.elapsedRealtime()
        val i = Intent(this, AlarmReceiver::class.java)
        mPendingIntent = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)
        mManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, (60 * 1000).toLong(), mPendingIntent)

    }

    fun registerReceiver() {
        IntentFilter().let { intentFilter ->
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED")
            intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED_REQUESTED")
            intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED")
            registerReceiver(mConnectReciver, intentFilter)
        }


        /*   IntentFilter().let { intentFilter ->
               intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED")
               intentFilter.priority = 1000
               registerReceiver(mSmsReceiver, intentFilter)

           }*/
    }

    /**
     * 获取客服信息的回调
     */
    override fun getSuccess(bean: ContactInfoBean) {
        bean.data?.let {
            BillPreference.saveObj2SP(PreferenceKeys.CONTACTINFO.name, it)
            it.phone?.let { Constans.CONTACT_PHONE_NUM = it }
        }

    }

    /**
     * 获取版本的回调
     */

    override fun update(bean: VersionResponseBean) {
        if (bean.data!!.version > AppInfoUtils.appVersionCode&&!Constans.ISCHECKUPGRADE) {
            Constans.ISCHECKUPGRADE=true
            Beta.checkUpgrade(false, false)
        }
    }


   /* private fun syncStep(step: Int) {
        if (step > 0) {
            mSyncStepPresenter.syncStep(SyncStepRequest(DeviceUtil.getLastConnectMac(), step), this)
        }
    }*/


   /* @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(syncStepEvent: SyncStepEvent) {
            syncStep(syncStepEvent.step)
    }*/


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(event: BluetoothSwitchEvent) {
        if (event.isOn) {
            if (DeviceUtil.getLastConnectMac().isNotEmpty() && isFirstOnBluetooth) {
                isFirstOnBluetooth = false
                BleManager.getInstance().connect(DeviceUtil.getLastConnectMac(), bleConnectCallback)
            }
        }
    }


   /* override fun syncStepFail(b: Boolean) {
        if(!b){
            EventBus.getDefault().post(SyncStepCount(BraceletApplication.watchCountStep))
        }
    }
*/
    override fun getVersion(bean: FirmwareVersionBean) {
    }


    /**
     * 性别选中事件
     *
     * @param view
     * @param ischanged
     */
    @OnCheckedChanged(R.id.mining, R.id.sport, R.id.mine)
    fun onRadioCheck(view: CompoundButton, ischanged: Boolean) {
        when (view.id) {
            R.id.mining -> if (ischanged) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                    StatusBarCompat.setTranslucent(window, true)
                }
                setFragment(mMiningFragment)
                if (!isFirstToMining) {
                    mMiningFragment.setResumeUi()
                } else {
                    isFirstToMining = false
                }
            }
            R.id.sport -> if (ischanged) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                    StatusBarCompat.setStatusBarColor(this, Color.WHITE, true)
                }
                setFragment(mSportFragment)
               /* BraceletApplication.zhBraceletService?.bleConnectState?.let {
                    if (it) BraceletApplication.zhBraceletService?.syncTime()
                }*/
            }

            R.id.mine -> if (ischanged) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                    StatusBarCompat.setTranslucent(window, true)
                }
                setFragment(mMineFragment)
                EventBus.getDefault().post(RefreshAssetsEvent())
            }
        }
    }


    fun setFragment(fragment: BaseFragment) {
        supportFragmentManager.beginTransaction().apply {
            currentFragment?.let { hide(it) }

            if (!fragment.isAdded) {
                add(R.id.frameLayout, fragment)
            } else {
                show(fragment)
            }
            currentFragment = fragment
        }.commitAllowingStateLoss()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (SystemClock.currentThreadTimeMillis() - currentMilli > 1500) {
                currentMilli = SystemClock.currentThreadTimeMillis()
//                ToastUtils.show(this,)
                toast(getString(R.string.再按一次返回键退出))
            } else {
                moveTaskToBack(true)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun createPresenter(): SyncStepPresenter {
        mSyncStepPresenter = SyncStepPresenter()
        return mSyncStepPresenter
    }


    private fun toggleNotificationListenerService() {
        packageManager.setComponentEnabledSetting(ComponentName(this, NLService::class.java), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
        packageManager.setComponentEnabledSetting(ComponentName(this, NLService::class.java), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)
    }





    override fun onDestroy() {
        unregisterReceiver(mConnectReciver)
        super.onDestroy()
    }

}




